<template>
  <div class="app-container" id="newStrategy">
    <el-form ref="form" :model="form" label-width="80px" :rules="addRules">
      <el-form-item label="活动名称">
        <el-input v-model="form.title" placeholder="请输入活动名称" class="w500"></el-input>
      </el-form-item>
      <el-form-item label="副标题">
        <el-input v-model="form.describe" placeholder="请输入副标题" class="w500"></el-input>
      </el-form-item>
      <el-form-item label="活动类别">
        <el-select v-model="activityType" placeholder="活动类别">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动标签">
        <el-tag :key="tag.id" v-for="tag in form.tags" :closable="true" :close-transition="false" @close="handleClose(tag)" style="margin-left:10px;">
          {{tag.tag}}
        </el-tag>
        <el-input class="input-new-tag" v-if="tagVisible" v-model="tagValue" ref="saveTagInput" size="mini" @keyup.enter.native="handleTagConfirm"
          @blur="handleTagConfirm">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showTag">+ 新标签</el-button>
      </el-form-item>
      <el-form-item label="活动人数">
        <el-input-number v-model="form.number" :controls="false"></el-input-number>
      </el-form-item>
      <el-form-item label="活动地点">
        <el-button @click="dialogTableVisible = true">{{address}}</el-button>
      </el-form-item>
      <el-dialog title="选择地址" :visible.sync="dialogTableVisible" top="15vh">
        <div class="amap-page-container">
          <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
          <el-amap vid="amap" :center="center" :zoom="zoom" :plugin="plugin" class="amap-demo" :events="events">
            <el-amap-marker :position="MakerPosition"></el-amap-marker>
          </el-amap>
          <div class="toolbar">
            <br /> 地址：{{ address }}
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogTableVisible = false">确 定</el-button>
      </span>
      </el-dialog>
      <el-form-item label="封面海报">
        <el-tabs v-model="changeImg" class="w500">
          <el-tab-pane label="海报图" name="first">
            <el-upload class="cover-uploader" action="http://www.jiatingyigou.com:7001/upload/img" :show-file-list="false" :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="coverImageUrl" :src="coverImageUrl" class="cover">
              <i v-else class="el-icon-plus cover-uploader-icon"></i>
              </el-upload>
          </el-tab-pane>
          <el-tab-pane label="封面图" name="second">
            <el-upload class="cover-uploader" action="http://www.jiatingyigou.com:7001/upload/img" :show-file-list="false" :on-success="handleAvatarSuccess2"
              :before-upload="beforeAvatarUpload">
              <img v-if="coverImageUrl2" :src="coverImageUrl2" class="cover">
              <i v-else class="el-icon-plus cover-uploader-icon"></i>
              </el-upload>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item label="活动日期">
        <el-date-picker v-model="form.time" type="date" placeholder="选择日期" format="yyyy-MM-dd" :picker-options="pickerOptions0">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动内容">
        <div class="changeText">HTML模式
          <el-switch v-model="openCode" on-text="" off-text="">
          </el-switch>
        </div>
        <el-input v-if="openCode==true" type="textarea" v-model="form.content" class="w500"></el-input>
        <quill-editor class="w500" v-else ref="myTextEditor" v-model="form.content" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
          @ready="onEditorReady($event)">
          </quill-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即发布</el-button>
        <el-button type="warning" @click="onSave">存为草稿</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="提示" :visible.sync="dialogAddressVisible" size="tiny">
      <span>请选择活动地址</span>
      <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogAddressVisible = false">取消</el-button>
    <el-button  @click="dialogAddressVisible = false" type="primary">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogSuccessVisible" size="tiny">
      <span>添加成功,是否跳转到首页？</span>
      <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogSuccessVisible = false">取消</el-button>
    <el-button  @click="GoToIndex" type="primary">确 定</el-button>
  </span>
    </el-dialog>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogAvatarVisible" size="tiny">
      <span>请选择完善活动信息</span>
      <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogAvatarVisible = false">取消</el-button>
    <el-button  @click="dialogAvatarVisible = false" type="primary">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>
<script>
 import dateFormat from '@/utils/date'
  import { isvalidStrategyContent } from "@/utils/validate";
  import { getToken } from "@/utils/auth";
  import {
    getActivityById,
    delActivityTag,
    addActivityTag,
    addActivity
  } from "@/api/activity";
  export default {
    data() {
      let self = this;
      const validateTitle = (rule, value, callback) => {
        if (!isvalidStrategyContent(value)) {
          callback(new Error("请输入正确的标题"));
        } else {
          callback();
        }
      };
      const validateDesc = (rule, value, callback) => {
        if (!isvalidStrategyContent(value)) {
          callback(new Error("请输入描述"));
        } else {
          callback();
        }
      };
      const validateContent = (rule, value, callback) => {
        if (!isvalidStrategyContent(value)) {
          callback(new Error("请输入内容"));
        } else {
          callback();
        }
      };
      return {
        status:1,
        u_id: "",
        activity_id: 0,
        updateId: 0,
        activityType: "",
        dialogSuccessVisible: false,
        dialogAddressVisible: false,
        dialogAvatarVisible: false,
        dialogTableVisible: false,
        tagValue: "",
        changeImg: "first",
        tagVisible: false,
        strategyType: "view",
        zoom: 12,
        center: [121.59996, 31.197646],
        address: "选择地址",
        describe: "",
        adcode: "",
        position: "",
        searchOption: {
          city: "全国",
          citylimit: true
        },
        plugin: [
          {
            pName: "Geolocation",
            events: {
              init(o) {
                o.getCurrentPosition((status, result) => {
                  if (result && result.position) {
                    console.log(result);
                    self.addressInfo.lng = result.position.lng;
                    self.addressInfo.lat = result.position.lat;
                    self.addressInfo.traffic = result.formattedAddress;
                    self.address = result.formattedAddress;
                    self.addressInfo.adcode = result.addressComponent.adcode;
                    self.addressInfo.position =
                      result.addressComponent.city +
                      "-" +
                      result.addressComponent.district;
                  }
                });
              }
            }
          }
        ],
        events: {
          click(e) {
            let { lng, lat } = e.lnglat;
            self.addressInfo.lng = lng;
            self.addressInfo.lat = lat;
            self.MakerPosition = [e.lnglat.lng, e.lnglat.lat];
            var geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: "all"
            });
            geocoder.getAddress([lng, lat], function (status, result) {
              if (status === "complete" && result.info === "OK") {
                if (result && result.regeocode) {
                  self.addressInfo.traffic = result.regeocode.formattedAddress;
                  self.address = result.regeocode.formattedAddress;
                  self.addressInfo.adcode =
                    result.regeocode.addressComponent.adcode;
                  self.addressInfo.position =
                    result.regeocode.addressComponent.city +
                    "-" +
                    result.regeocode.addressComponent.district;
                  self.$nextTick();
                }
              }
            });
          }
        },
        MakerPosition: [121.59996, 31.197646],
        lng: 0,
        lat: 0,
        openCode: false,
        startSellTime: "",
        endSellTime: "",
        typeOptions: [
          {
            value: "热门",
            label: "热门"
          },
          {
            value: "音乐",
            label: "音乐"
          },
          {
            value: "美食",
            label: "美食"
          },
          {
            value: "运动",
            label: "运动"
          },
          {
            value: "旅行",
            label: "旅行"
          }
        ],
        form: {
          u_id: "",
          title: "",
          type: "",
          typeName: "",
          describe: "",
          time: "",
          number: "",
          content: "<p>请输入活动内容...</p>",
          cover: "",
          imgurl: "",
          tags: []
        },
        addressInfo: {
          lat: "",
          lng: "",
          position: "",
          traffic: "",
          adcode: ""
        },
        coverImageUrl: "",
        coverImageUrl2: "",
        addRules: {
          name: [{ required: true, trigger: "blur", validator: validateTitle }],
          describe: [
            { required: true, trigger: "blur", validator: validateDesc }
          ],
          content: [
            { required: true, trigger: "blur", validator: validateContent }
          ]
        },
        editorOption: {
          modules: {
            toolbar: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote", "code-block"],
              [{ header: 1 }, { header: 2 }],
              [{ list: "ordered" }, { list: "bullet" }],
              [{ script: "sub" }, { script: "super" }],
              [{ indent: "-1" }, { indent: "+1" }],
              [{ direction: "rtl" }],
              [{ size: ["small", false, "large", "huge"] }],
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ font: [] }],
              [{ color: [] }, { background: [] }],
              [{ align: [] }],
              ["clean"],
              ["image"]
            ],
            syntax: {
              highlight: text => hljs.highlightAuto(text).value
            }
          }
        }
      };
    },
    created() {
      let id = this.$route.query.id;
      
      if (id) {
        this.activity_id = id
        getActivityById(id).then(res => {
          if (res.message == "ok") {
            this.updateId = res.activity.id;
            this.form.title = res.activity.title;
            this.u_id = res.activity.u_id;
            this.form.cover = res.activity.cover;
            this.form.imgurl = res.activity.imgurl;
            this.form.typeName = res.activity.typeName;
            this.form.number = res.activity.number;
            this.activityType = res.activity.typeName;
            this.form.describe = res.activity.describe;
            this.coverImageUrl = res.activity.cover;
            this.coverImageUrl2 = res.activity.imgurl;
            this.form.time = res.activity.time;
            this.form.content = res.detail.content;
            this.form.type = res.activity.type;
            this.form.tags = res.tags;
            this.addressInfo.lat = res.activity.lat;
            this.addressInfo.lng = res.activity.lng;
            this.addressInfo.position = res.activity.address;
            this.addressInfo.adcode = res.activity.adcode;
            this.addressInfo.traffic = res.activity.traffic;
            this.address = res.activity.traffic;
          
          }
        });
      } else {
        this.u_id = getToken()
      }
    },
    methods: {
      onEditorBlur(editor) {
        // console.log('editor blur!', editor)
      },
      onEditorFocus(editor) {
        // console.log('editor focus!', editor)
      },
      onEditorReady(editor) {
        // console.log('editor ready!', editor)
      },
      onSave() {
        this.status = 0;
        this.onSubmit();
      },
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      onSubmit() {
        if (this.address == "选择地址") {
          this.dialogAddressVisible = true;
          return;
        }
        

        if (
          this.form.title == "" ||
         this.activityType=="" ||
          this.form.describe == "" ||
          this.form.content == "" ||
          this.form.time == "" ||
          this.form.cover == "" ||
          this.form.imgurl == "" ||
          this.form.number == ""
        ) {
          this.dialogAvatarVisible = true;
          return;
        }

        if (this.activityType == "热门") {
          this.form.type = "hot"
        } else if (this.activityType == "音乐") {
          this.form.type = "music"
        } else if (this.activityType == "美食") {
          this.form.type = "food"
        } else if (this.activityType == "运动") {
          this.form.type = "sport"
        } if (this.activityType == "旅行") {
          this.form.type = "trip"
        }
        this.form.u_id = this.u_id
        this.form.activity_id = this.activity_id*1
        this.form.typeName = this.activityType
         this.form.status = this.status
        let forDate =  new Date(this.form.time).getTime()
        this.form.time = dateFormat(new Date(forDate * 1), 'yyyy-MM-dd')
        
        addActivity(this.form, this.addressInfo).then((res) => {
          
          if (res.message == "success") {
            
            if (this.activity_id == 0) {
              this.form.tags.map((tag, index) => {
                addActivityTag(res.activity_id, tag.tag).then((resTag) => {
                  if (resTag.message == "ok" && index == this.form.tags.length - 1) {
                    this.$message({
                      message: "活动已添加",
                      type: "success"
                    });
                    this.$router.push({ path: "/activity/index" })
                  }
                })
              })
            } else {
              this.$message({
                message: "活动已更新",
                type: "success"
              });
              this.$router.push({ path: "/activity/index" })
            }
          }
        })

      },
      handleClose(tag) {

        delActivityTag(tag.id).then((res) => {
          if (res.message == "ok") {
            this.form.tags.splice(this.form.tags.indexOf(tag), 1);
            this.$message({
              message: "标签已删除",
              type: "success"
            });
          }
        })
      },

      showTag() {
        this.tagVisible = true;
        this.$nextTick(_ => {

          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleTagConfirm() {
         this.tagVisible = false;
        if (this.tagValue.trim() == "") {
          return
        }

        let tagValue = this.tagValue;
        let id = 0
        if (this.activity_id != 0) {
          addActivityTag(this.activity_id, tagValue).then((res) => {
            if (res.message == "ok") {
              id = res.id
              this.$message({
                message: "添加标签成功",
                type: "success"
              });

              this.form.tags.push({ tag: tagValue, id });
             
              this.tagValue = "";
            }
          })

        } else {
          this.form.tags.push({ tag: tagValue });
        }
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      GoToIndex() {
        this.$router.push({ path: "/" });
      },
      handlePreview(file) {
        console.log(file);
      },
      handleAvatarSuccess(res, file) {
        this.coverImageUrl = URL.createObjectURL(file.raw);
        this.form.cover = "http://" + res.data.url;
        this.$message({
          message: "上传成功",
          type: "success"
        });
      },
      handleAvatarSuccess2(res, file) {
        this.coverImageUrl2 = URL.createObjectURL(file.raw);
        this.form.imgurl = "http://" + res.data.url;
        this.$message({
          message: "上传成功",
          type: "success"
        });
      },
      beforeAvatarUpload(file) {
        this.$message("正在上传...");
        const isJPG = file.type === "image/jpeg" || file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error("上传封面图片只能是 JPG/PNG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传封面图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      },
      addMarker: function () {
        let lng = 121.5 + Math.round(Math.random() * 1000) / 10000;
        let lat = 31.197646 + Math.round(Math.random() * 500) / 10000;
        this.MakerPosition = [lng, lat];
      },
      onSearchResult(pois) {
        var self = this;
        let latSum = 0;
        let lngSum = 0;
        if (pois.length > 0) {
          pois.forEach(poi => {
            let { lng, lat } = poi;
            lngSum += lng;
            latSum += lat;
            this.MakerPosition = [poi.lng, poi.lat];
            var geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: "all"
            });
            geocoder.getAddress([poi.lng, poi.lat], function (status, result) {
              if (status === "complete" && result.info === "OK") {
                if (result && result.regeocode) {
                  self.addressInfo.traffic = result.regeocode.formattedAddress;
                  self.addressInfo.lat = poi.lat;
                  self.addressInfo.lng = poi.lng;
                  self.addressInfo.adcode =
                    result.regeocode.addressComponent.adcode;
                  self.addressInfo.position =
                    result.regeocode.addressComponent.city +
                    "-" +
                    result.regeocode.addressComponent.district;
                  self.address = result.regeocode.formattedAddress;
                  self.$nextTick();
                }
              }
            });
          });
          let center = {
            lng: lngSum / pois.length,
            lat: latSum / pois.length
          };
          this.center = [center.lng, center.lat];
        }
      }
    }
  };

</script>
<style>
  .amap-demo {
    height: 300px;
  }
  
  .search-box {
    position: absolute;
    top: 25px;
    left: 20px;
  }
  
  #newStrategy .el-vue-search-box-container {
    position: absolute;
  }
  
  .amap-page-container {
    position: relative;
    height: 360px;
  }
  
  .cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  
  .cover-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  
  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  
  .cover {
    width: 178px;
    height: 178px;
    display: block;
  }
  .w500 {
  width: 500px;
}
</style>